package com.example.flipperview;

import android.content.Context;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.LinearLayout;


public class ViewFlipper extends LinearLayout {
    private final int MAX_SHOW_ITEM_SIZE = 5;
    private IAdapter mIAdapter;
    private int mCount;

    //最后一个item动画
    private Animation mLastOneAnimation;

    //其它item动画
    private Animation mCommonAnimation;

    //数据下标
    private int mCurrentIndex;

    /**
     * 这里动画时间是4秒，所以间隔得大于动画时间
     */
    private static final int DEFAULT_INTERVAL = 4000;

    private int mFlipInterval = DEFAULT_INTERVAL;


    private boolean mRunning = false;
    private boolean inRunning = false;
    private boolean mVisible = false;
    private boolean mUserPresent = true;


    // region 构造函数
    public ViewFlipper(Context context) {
        super(context);
        init(context);
    }

    public ViewFlipper(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public ViewFlipper(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    private void init(Context context) {
        this.setOrientation(LinearLayout.VERTICAL);
    }
    // endregion





    @Override
    protected void onWindowVisibilityChanged(int visibility) {
        super.onWindowVisibilityChanged(visibility);
        mVisible = visibility == VISIBLE;
        updateRunning(mVisible);
    }






    // region 开始、停止滚动
    public void startFlipping() {
        inRunning = true;
        updateRunning();
    }

    public void stopFlipping() {
        inRunning = false;
        updateRunning();
    }
    // endregion

    private void updateRunning() {
        updateRunning(true);
    }





    //  region 设置 需要滚动的 View
    public void setIAdapter(IAdapter iAdapter) {
        this.mIAdapter = iAdapter;
        initShowItems();
    }

    /**
     * 初始化childViews
     */
    private void initShowItems() {
        if(mIAdapter==null){
            return;
        }

        mCount = mIAdapter.getCount();

        for (int i = 0; i < mCount; i++) {
            if (i == MAX_SHOW_ITEM_SIZE) {
                break;
            }
            View convertView = getChildAt(i);
            View item = mIAdapter.getItemView(convertView, i);
            addView(item, i);
        }
    }
    // endregion


    private void updateRunning(boolean flipNow) {
        boolean running = mVisible && inRunning && mUserPresent;
        if (running != mRunning) {
            if (running /*&& (mCount > MAX_SHOW_ITEM_SIZE)*/) {
                showItems(mCurrentIndex++, flipNow);
                Message msg = mHandler.obtainMessage(FLIP_MSG);
                mHandler.sendMessageDelayed(msg, mFlipInterval);
            } else {
                mHandler.removeMessages(FLIP_MSG);
            }
            mRunning = running;
        }
    }


    private void showItems(final int position, boolean animate) {
        if (animate && (mLastOneAnimation == null || mCommonAnimation == null)) {
            mLastOneAnimation = AnimationUtils.loadAnimation(getContext(), R.anim.lastone_anim);
            mCommonAnimation = AnimationUtils.loadAnimation(getContext(), R.anim.common_anim);
        }
        int childCount = getChildCount();
        for (int i = 0; i < childCount; i++) {
            View child = getChildAt(i);
            child.clearAnimation();
            int index = position + i;
            child = mIAdapter.getItemView(child, (index >= mIAdapter.getCount()) ? (index - mIAdapter.getCount()) : index);
            if (animate) {
            /*    if(i==0){
                    child.setBackgroundColor(Color.GRAY);
                    child.setAnimation(mCommonAnimation);
                }else */

                    if (i == childCount - 1) {
                    child.setAnimation(mLastOneAnimation);
//                    child.setBackgroundColor(Color.RED);
                } else {
                    child.setAnimation(mCommonAnimation);
//                    child.setBackgroundColor(Color.BLUE);
                }
            }
        }
        if (animate) {
            mCommonAnimation.startNow();
            mLastOneAnimation.startNow();
        }

        //保证传入的position小于getCount
        if (mCurrentIndex >= mIAdapter.getCount()) {
            mCurrentIndex = 0;
        }
    }

    private final int FLIP_MSG = 1;

    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == FLIP_MSG) {
                if (mRunning) {
                    showItems(mCurrentIndex++, true);
                    msg = obtainMessage(FLIP_MSG);
                    sendMessageDelayed(msg, mFlipInterval);
                }
            }
        }
    };



}
